package me.zhengjie.modules.sync.processing;

import cn.hutool.core.math.MathUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSON;
import com.qiaofang.applet.common.constant.SyncTypeEnum;
import com.qiaofang.applet.common.util.RedisKeyUtil;
import com.qiaofang.applet.common.util.RedisUtil;
import com.qiaofang.applet.constants.UpDownFlagConstants;
import com.qiaofang.applet.service.other.service.ProvinceCityService;
import com.qiaofang.applet.service.property.domain.*;
import com.qiaofang.applet.service.property.service.FirsthandEstateService;
import com.qiaofang.applet.service.property.service.mapstruct.FirsthandEstateMapper;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.sync.ProcessingBase;
import me.zhengjie.utils.ImageUtil;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.NumberUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;

@Slf4j
@Service
public class FirsthandEstateSyncProcessing extends ProcessingBase {
    @Autowired
    private FirsthandEstateService firsthandEstateService;

    @Autowired
    private ProvinceCityService provinceCityService;

    @Autowired
    private FirsthandEstateMapper firsthandEstateMapper;

    @Autowired
    private RedisUtil redisUtil;


    public FirsthandEstateSyncProcessing(){
        setDataType(SyncTypeEnum.FIRST_PRO.getSyncType());
    }

    @Override
    protected void processing(SyncDataQueue syncDataQueue) {
        String batchContent=syncDataQueue.getBatchContent();
        List<FirsthandEstate> list= JSON.parseArray(batchContent,FirsthandEstate.class);
        if(null==list){
            log.info("processing firsthandEstate is null");
            return;
        }
        Map<String,String> map=getNameMap(list);
        list.stream().forEach(item->{
            saveFirsthandEstate(item,map,syncDataQueue);
        });

    }

    private void saveFirsthandEstate(FirsthandEstate item,Map<String,String> map,SyncDataQueue syncDataQueue){
        String estateUniqueUuid=syncDataQueue.getCompanyUuid()+"_"+item.getEstateUuid();
        FirsthandEstate firsthandEstate= firsthandEstateService.findByEstateUniqueUuid(estateUniqueUuid);
        if(!Objects.isNull(item.getDeleted()) && item.getDeleted()){
            if (!Objects.isNull(firsthandEstate)) {
                firsthandEstateService.deleteById(firsthandEstate.getId());
            }
            return;
        }
        if(Objects.isNull(firsthandEstate)){
            firsthandEstate=new FirsthandEstate();
            firsthandEstate.setRecommend(false);
        }
        //复制属性
        String[] ignoreProperties=new String[] { "id","recommend","upDownFlag", "manualUpTime", "createBy","updateBy","createTime","updateTime" };
        BeanUtils.copyProperties(item,firsthandEstate,ignoreProperties);
        firsthandEstate.setCompanyUuid(syncDataQueue.getCompanyUuid());
        firsthandEstate.setCityCode(syncDataQueue.getCityCode());
        firsthandEstate.setCorporationCode(syncDataQueue.getCorporationCode());
        firsthandEstate.setUpdateTime(new Date());
        firsthandEstate.setLastSyncDate(new Date(System.currentTimeMillis() - DateUtil.DAY_MILLISECONDS));
        firsthandEstate.setProvinceName(map.get(firsthandEstate.getProvince()));
        firsthandEstate.setCityName(map.get(firsthandEstate.getCity()));
        firsthandEstate.setAreaName(map.get(firsthandEstate.getArea()));
        firsthandEstate.setEstateUniqueUuid(estateUniqueUuid);
        //过滤删除的户型和图片
        filterByDeleted(firsthandEstate);
        //替换域名
        replaceDomain(firsthandEstate);
        //设置首图
        firsthandEstate.setImageUrl(firsthandEstateMapper.getCoverImageUrl(firsthandEstate));

        //设置最小和最大面积
        firsthandEstateMapper.setMinAndMaxBuildingArea(firsthandEstate);
        //设置户型图图片
        setEstateHouseTypeImageUrl(firsthandEstate);
        //设置大最大和最小面积
        firsthandEstate.setBuildingAreaRange(firsthandEstateMapper.getBuildingAreaRange(firsthandEstate));
        //默认下架
        firsthandEstate.setUpDownFlag(UpDownFlagConstants.DOWN_FLAG.getValue());
        //新房最低总价和最高总价处理
        handleFirstEstateTotalPrice(firsthandEstate);
        //售罄楼盘不进行上下架处理
        if (!"6".equals(firsthandEstate.getSaleStatus())) {
            firsthandEstate.setRulesHandle(false);
        }

        firsthandEstate.setRelationUpdate(true);

        //删除新房图片水印缓存
        redisUtil.hdel(RedisKeyUtil.getPropertyWaterMarkKey(syncDataQueue.getCompanyUuid()), estateUniqueUuid);
        try {
            firsthandEstateService.save(firsthandEstate);
        } catch (Exception e) {
            log.error("saveFirsthandEstate error",e);
            //记录错误日志
            this.saveErrorLog(JSON.toJSONString(firsthandEstate),e.getMessage(),syncDataQueue);
        }
    }
    //过滤删除的户型和图片
    private void filterByDeleted(FirsthandEstate firsthandEstate){
        List<EstateHouseType> estateHouseTypeList = firsthandEstate.getHouseTypeList();
        if (!CollectionUtils.isEmpty(estateHouseTypeList)) {
            Iterator<EstateHouseType> estateHouseTypeIterator=estateHouseTypeList.iterator();

            while(estateHouseTypeIterator.hasNext()){
                EstateHouseType estateHouseType=estateHouseTypeIterator.next();
                if(!Objects.isNull(estateHouseType.getDeleted()) && estateHouseType.getDeleted()){
                    estateHouseTypeIterator.remove();
                }
            }
        }
        List<EstateImage> images = firsthandEstate.getImageList();
        if (!CollectionUtils.isEmpty(images)) {
            Iterator<EstateImage> imagesIterator=images.iterator();
            while( imagesIterator.hasNext()){
                EstateImage estateImage=imagesIterator.next();
                if(!Objects.isNull(estateImage.getDeleted()) && estateImage.getDeleted()){
                    imagesIterator.remove();
                }
            }
        }
        List<EstateDynamic> estateDynamicList=firsthandEstate.getDynamicList();
        if (!CollectionUtils.isEmpty(estateDynamicList)) {
            Iterator<EstateDynamic> estateDynamicIterator=estateDynamicList.iterator();
            while( estateDynamicIterator.hasNext()){
                EstateDynamic estateDynamic=estateDynamicIterator.next();
                if(!Objects.isNull(estateDynamic.getDeleted()) && estateDynamic.getDeleted()){
                    estateDynamicIterator.remove();
                }
            }
        }
        List<EstatePrincipal> estatePrincipalList=firsthandEstate.getPrincipalList();
        if (!CollectionUtils.isEmpty(estateDynamicList)) {
            Iterator<EstatePrincipal> estatePrincipalIterator=estatePrincipalList.iterator();
            while( estatePrincipalIterator.hasNext()){
                EstatePrincipal estatePrincipal=estatePrincipalIterator.next();
                if(!Objects.isNull(estatePrincipal.getDeleted()) && estatePrincipal.getDeleted()){
                    estatePrincipalIterator.remove();
                }
            }
        }


    }
    //设置户型图
    private void setEstateHouseTypeImageUrl(FirsthandEstate firsthandEstate){
        List<EstateHouseType> estateHouseTypeList = firsthandEstate.getHouseTypeList();
        List<EstateImage> images = firsthandEstate.getImageList();
        if (CollectionUtils.isEmpty(estateHouseTypeList)) {
            return;
        }
        if (CollectionUtils.isEmpty(images)) {
            return;
        }
        for(EstateHouseType houseType : estateHouseTypeList){
            Boolean deleted=houseType.getDeleted();
            String houseTypeUuid=houseType.getHouseTypeUuid();
            if(Objects.isNull(deleted) || Objects.isNull(houseTypeUuid) || deleted){
                continue;
            }
            for(EstateImage estateImage : images){
                if(Objects.isNull(estateImage.getDeleted()) || Objects.isNull(estateImage.getBusinessUuid()) || estateImage.getDeleted()){
                    continue;
                }
                if(estateImage.getBusinessUuid().equals(houseTypeUuid)){
                    houseType.setImageUrl(estateImage.getImageUrl());
                }
            }
        }

    }

    //替换域名
    private void replaceDomain(FirsthandEstate firsthandEstate){
        List<EstateImage> estateImageList= firsthandEstate.getImageList();
        if(null==estateImageList) return;
        for(EstateImage estateImage : estateImageList){
            String replaceUrl = StringUtils.replace(estateImage.getImageUrl(), ImageUtil.DISCARD_IMAGE_URL, ImageUtil.IMAGE_URL);
            //replaceUrl = StringUtils.replace(replaceUrl,ImageUtil.HTTP, ImageUtil.HTTPS);
            estateImage.setImageUrl(replaceUrl);
        }
    }

    private Map<String,String> getNameMap(List<FirsthandEstate> list){
        Set<String> codes=new HashSet<>();
        for(FirsthandEstate firsthandEstate :list){
            String province= firsthandEstate.getProvince();
            String city= firsthandEstate.getCity();
            String area= firsthandEstate.getArea();
            if(!StringUtils.isEmpty(province)){
                codes.add(firsthandEstate.getProvince());
            }
            if(!StringUtils.isEmpty(city)){
                codes.add(city);
            }
            if(!StringUtils.isEmpty(area)){
                codes.add(area);
            }
        }
        if(CollectionUtils.isEmpty(codes)){
            return  new HashMap<>();
        }
        return provinceCityService.getCityOrAreaName(new ArrayList<>(codes));
    }

    private void handleFirstEstateTotalPrice(FirsthandEstate firsthandEstate) {
        //均价
        BigDecimal averagePrice = firsthandEstate.getAveragePrice();
        if (averagePrice == null || StringUtils.isEmpty(firsthandEstate.getBuildingAreaRange())) {
            return;
        }
        //单位：万
        BigDecimal price = NumberUtil.div(averagePrice, 10000, 2);
        //如果最大的户型面积不存在，那么最大户型面积和最小户型面积相等
        if (firsthandEstate.getMaxBuildingArea() == null) {
            BigDecimal totalPrice = NumberUtil.mul(price, firsthandEstate.getMinBuildingArea());
            firsthandEstate.setMinTotalPrice(totalPrice);
            firsthandEstate.setMaxTotalPrice(totalPrice);
        }
        if (firsthandEstate.getMinBuildingArea() != null) {
            firsthandEstate.setMinTotalPrice(NumberUtil.mul(price, firsthandEstate.getMinBuildingArea()));
        }
        if (firsthandEstate.getMaxBuildingArea() != null) {
            firsthandEstate.setMaxTotalPrice(NumberUtil.mul(price, firsthandEstate.getMaxBuildingArea()));
        }
    }
}
